function [acom,varargout]=VARcompanion(a,sigma,const)
%Name VARCOMPANION
%[acom, scom, dcom]=VARcompanion(a,sigma,const)
%purpose: constructs companion matrix for VAR(p) model
%input : - Parameter matrix a
%        - variance covarance matrix sigma 
%        - constant const (0/1/2)     
%output: - companion matrix acom
%        - variance-covariance matrix of VAR(1) representation (optional)
%        - vector of constants dcom (optional)
%author: Ulrich Woitek, 2.9.2003
dim=size(a,1);
if const==1
    dcom=a(:,1);
    a=a(:,2:end);
elseif const==2
    dcom=a(:,1);
    tcom=a(:,2);
    a=a(:,3:end);
elseif const==0
    dcom=zeros(dim,1);
elseif const>2
    dcom=a(:,1:const);
    a=a(:,const+1:end);
end
p=size(a,2)/dim;
s=sigma;
if p >1
    a2 = eye(size(a,2)-dim);
    a3 = zeros(size(a,2)-dim,dim);
    acom = [a; a2 a3];
    if nargout>1
        dcom=[dcom;zeros(size(a,2)-dim,1)];
        s=[s;(zeros(dim*(p-1),dim))];
        scom=[s (zeros(dim*p,dim*(p-1)))];
        varargout{1}=scom;
        varargout{2}=dcom;
    end
else
    acom=a;
    if nargout>1
        scom=s;
        varargout{1}=scom;
        varargout{2}=dcom;
    end
end